#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<vector>

using namespace std;
 
 struct TreeNode {
     int val;
     TreeNode *left;
     TreeNode *right;
     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 };
 
class Solution {
public:
    TreeNode* buildtree(vector<int>& preorder, int pleft, int pright, vector<int>& inorder, int ileft, int iright)
    {
        if (pleft > pright || ileft > iright)
            return nullptr;

        if (pleft == pright || ileft == iright)
            return new TreeNode(preorder[pleft]);

        while ((ileft <= iright) && (inorder[ileft] != preorder[pleft]))
        {
            ileft++;
        }
        while ((pleft < pright) && (preorder[pright] != inorder[ileft - 1]))
        {
            pright--;
        }
        TreeNode* root = new TreeNode(preorder[pleft]);
        root->left = buildtree(preorder, pleft + 1, pright, inorder, 0, ileft - 1);
        root->right = buildtree(preorder, pright + 1, preorder.size() - 1, inorder, ileft + 1, inorder.size() - 1);

        return root;;
    }

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return buildtree(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1);
    }
};

int main()
{
    vector<int> preorder = {1,2};
    vector<int> inorder = {1,2};
    Solution s;
    TreeNode* ret = s.buildTree(preorder,inorder);
}